var GameField = EventDispatcher.extend({

	snake: null,
	snakeFood: null,
	width: null,
	height: null,
	userInterface: null,
	infoLayer: null,
	
	constructor: function(userInterface)
	{
		this.infoLayer = $('#infoLayer');
		this.userInterface = userInterface;
		this.userInterface.addListener(UserInterface.GAME_STATE_CHANGE, this, this.onGameStateChange);
		this.userInterface.addListener(UserInterface.DIRECTION_CHANGE, this, this.onDirectionChange);
		this.snake = new Snake();
		this.snake.addListener('move', this, this.onSnakeMove);
		this.snake.addListener('collision', this, this.onSnakeCollision);
		var foodPosition = this.getNewFoodPosition();
		this.snakeFood = new SnakeFood(foodPosition .x, foodPosition.y);
	},
	
	onGameStateChange: function(gameState)
	{
		if (gameState == GAME_STATE.PLAYING)
		{
			this.infoLayer.hide();
			this.snake.startMoving();
		}
		else if (gameState == GAME_STATE.PAUSED)
		{
			this.infoLayer.show();
			this.snake.stopMoving();
		}
		else if (gameState == GAME_STATE.RESTART)
		{
			this.infoLayer.hide();
			this.snake.restart();
		}
	},
	
	onDirectionChange: function(direction)
	{
		this.snake.setDirection(direction);
	},
	
	stopGame: function()
	{
		this.infoLayer.show();
		this.snake.stopMoving();
		this.userInterface.setGameState(GAME_STATE.GAME_OVER);
	},
	
	pauseGame: function()
	{
		this.snake.stopMoving();
	},
	
	startGame: function()
	{
		this.snake.startMoving();
	},
	
	restartGame: function()
	{
		this.snake.restart();
	},
	
	onSnakeMove: function()
	{
		if (this.didSnakeEatFood())
		{
			this.dispatchEvent('score');
			this.snake.grow();
			var newFoodPosition = this.getNewFoodPosition();
			this.snakeFood.x = newFoodPosition.x;
			this.snakeFood.y = newFoodPosition.y;
		}
	},
	
	didSnakeEatFood: function()
	{
		return this.snake.head.contains(this.snakeFood);
	},
	
	onSnakeCollision: function(keynum)
	{
		this.stopGame();
	},
	
	getNewFoodPosition: function()
	{
		var position = new Point();
		do {
			position = this.getRandomPosition(); 
		} while (this.snake.containsCoords(position.x, position.y));
		return position;
	},
	
	getRandomPosition: function()
	{
		var randomX = Math.floor(Math.random() * stage.width / SnakeSegment.SIZE) * SnakeSegment.SIZE;
		var randomY = Math.floor(Math.random() * stage.height / SnakeSegment.SIZE) * SnakeSegment.SIZE;
		return new Point(randomX, randomY);
	}
	
});